package com.kun.lagou.service.impl;

import com.kun.lagou.dao.UrlMapDao;
import com.kun.lagou.entity.UrlMap;
import com.kun.lagou.util.Base62Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author Administrator
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UrlMapService {
    private final UrlMapDao urlMapDao;

    @Transactional(rollbackFor = Exception.class)
    public String encode(String longUrl) {
        //这里需要加锁吗？真的需要先查询吗？
        UrlMap urlMap = urlMapDao.findFirstByLongUrl(longUrl);
        //答：可以不用，小概率事件，参考乐观锁、悲观锁
        if(urlMap == null) {
            urlMap = urlMapDao.save(UrlMap.builder().longUrl(longUrl).build());
        }

        return Base62Util.idToString(urlMap.getId());
    }

    public Optional<String> decode(String shortKey) {
        long id = Base62Util.stringToId(shortKey);
        return urlMapDao.findById(id).map(UrlMap::getLongUrl);
    }
}
